package rjeutsky.filters;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import rjeutsky.ControllerWrapper;
import rjeutsky.models.User;
import rjeutsky.validators.interfaces.Validator;

/**
 * Servlet Filter implementation class RegistrationValidator
 */
@WebFilter(filterName = "RegistrationValidator", urlPatterns = {"/AddUser"})
public class RegistrationValidator implements Filter {

	FilterConfig config;
	
    /**
     * Default constructor. 
     */
    public RegistrationValidator() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		String login = request.getParameter("login");
		String password = request.getParameter("password");
		User user = new User();
		user.setLogin(login);
		user.setPassword(password);
		Validator<User> v = ControllerWrapper.getApplicationController().getUserValidator();
		if (!v.validate(user)) {
			String message = URLEncoder.encode(v.getValidationErrorMessage(), "UTF-8");
			config.getServletContext().getRequestDispatcher("/Login.jsp?validationError=" + message).forward(request, response);
			return;
		}

		// pass the request along the filter chain
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		config = fConfig;
	}

}
